<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" :xs="24">
        <el-form
          v-show="showSearch"
          ref="queryForm"
          :model="queryParams"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="人员姓名" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="老人名字"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="phonenumber">
            <el-input
              v-model="queryParams.phoneNumber"
              placeholder="请输入手机号码"
              clearable
              size="small"
              style="width: 240px"
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="mini"
              @click="handleQuery"
            >搜索</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
              v-hasPermission="['personal:elderly:add']"
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAdd"
            >新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermission="['personal:elderly:delete']"
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDelete"
            >删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              v-hasPermission="['personal:elderly:export']"
              type="warning"
              plain
              icon="el-icon-download"
              size="mini"
              :loading="exportLoading"
              @click="handleExport"
            >导出</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-upload
              action="upload"
              class="upload-demo"
              :http-request="handleUpload"
              name="file"
              :show-file-list="false"
              accept=".xls, .xlsx"
              :before-upload="handleBeforeUpload"
            >
              <el-button
                v-hasPermission="['personal:elderly:upload']"
                type="success"
                plain
                icon="el-icon-upload"
                size="mini"
              >导入</el-button>
            </el-upload>
          </el-col>
        </el-row>

        <el-table v-loading="loading" :data="elderlyList" style="width: 100%" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column label="序号" type="index" align="center" />
          <el-table-column prop="name" label="名字" align="center" show-overflow-tooltip />
          <el-table-column prop="sex" label="性别" align="center" width="60">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.sex === '0'">男</el-tag>
              <el-tag v-else-if="scope.row.sex === '1'" type="danger">女</el-tag>
              <el-tag v-else type="warning">未知</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="age" label="年龄" align="center" />
          <el-table-column prop="height" label="身高/cm" align="center" >
            <template slot-scope="scope">
              {{ scope.row.height + 'cm' }}
            </template>
          </el-table-column>
          <el-table-column prop="weight" label="体重/kg" align="center" >
            <template slot-scope="scope">
              {{ scope.row.weight + 'kg' }}
            </template>
          </el-table-column>
          <el-table-column prop="address" label="地址" align="center" show-overflow-tooltip />
          <el-table-column prop="telForRelatives" label="亲属预留电话" align="center" />
          <el-table-column prop="nameForRelatives" label="预留亲属名字" align="center" />
          <el-table-column prop="identityId" label="身份证号" align="center" show-overflow-tooltip />
          <el-table-column prop="phoneNumber" label="手机号码" align="center" />
          <el-table-column
            label="操作"
            align="center"
            width="200"
            class-name="small-padding fixed-width"
          >
            <template v-if="scope.row.id !== 1" slot-scope="scope">
              <el-button
                v-hasPermission="['personal:elderly:update']"
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
              >修改</el-button>
              <el-button
                v-hasPermission="['personal:elderly:delete']"
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <el-pagination
      :page-size.sync="queryParams.pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      :page-sizes="[10, 20, 30, 40]"
      :current-page.sync="queryParams.pageNum"
      @current-change="getList"
      @size-change="getList"
    />
    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="姓名" prop="name">
              <el-input
                v-model="form.name"
                placeholder="请输入老人名字"
                maxlength="32"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="身份证" prop="identityId">
              <el-input
                v-model="form.identityId"
                placeholder="请输入身份证号"
                maxlength="18"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="性别">
              <el-select v-model="form.sex" placeholder="请选择">
                <el-option :key="'0'" label="男" :value="'0'" />
                <el-option :key="'1'" label="女" :value="'1'" />
                <el-option :key="'2'" label="未知" :value="'2'" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="绑定用户" prop="userId">
              <el-select
                ref="userId"
                v-model="form.userId"
                style="width:100%"
                placeholder="请输入用户名或用户昵称"
                filterable
                remote
                default-first-option
                clearable
                :remote-method="(query) => { searchInput(query) }"
                :loading="loading"
              >
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="'用户名: '+ item.userName + ' 名称：' + item.nickName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="身高/cm" prop="height">
              <el-input-number v-model="form.height" :precision="2" :min="0" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="体重/kg" prop="weight">
              <el-input-number v-model="form.weight" :precision="2" :min="0" :max="999" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phoneNumber">
              <el-input
                v-model="form.phoneNumber"
                placeholder="请输入手机号码"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="年龄" prop="age">
              <el-input-number
                v-model.number="form.age"
                placeholder="请输入年龄"
                style="width: 100%"
                :min="0"
                :max="999"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="地址" prop="address">
              <el-input
                v-model="form.address"
                placeholder="请输入地址"
                maxlength="124"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item
              label="家属电话"
              prop="telForRelatives"
            >
              <el-input
                v-model="form.telForRelatives"
                placeholder="请输入家属电话"
                maxlength="11"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item
              label="家属名字"
              prop="nameForRelatives"
            >
              <el-input
                v-model="form.nameForRelatives"
                placeholder="请输入家属名字"
                maxlength="32"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
// import { getToken } from '@/utils/auth'
import {
  addElderly,
  delElderly,
  exportElderly,
  getElderly,
  listElderly, queryUser,
  updateElderly,
  uploadExcel
} from '@/api/personal/elderly'
export default {
  name: 'Elderly',
  data() {
    var checkIdentityId = (rule, value, callback) => {
      const _IDRe18 = /^([1-6][1-9]|50)\d{4}(18|19|20)\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/
      const _IDre15 = /^([1-6][1-9]|50)\d{4}\d{2}((0[1-9])|10|11|12)(([0-2][1-9])|10|20|30|31)\d{3}$/
      // 校验身份证：
      if (!_IDRe18.test(value) && !_IDre15.test(value)) {
        callback(new Error('身份证号格式不对'))
      } else {
        callback()
      }
    }
    return {
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        phoneNumber: undefined
      },
      userList: [],
      title: '',
      userOptions: [],
      // 是否显示弹出层
      open: false,
      exportLoading: false,
      // 表单校验,
      rules: {
        name: [
          { required: true, message: '用户名称不能为空', trigger: 'blur' },
          {
            min: 2,
            max: 32,
            message: '用户名称长度必须介于 2 和 32 之间',
            trigger: 'blur'
          }
        ],
        identityId: [
          { required: true, message: '身份证号不能为空', trigger: 'blur' },
          { validator: checkIdentityId, trigger: 'blur' }
        ],
        age: [
          { type: 'number', message: '年龄必须为数字', trigger: 'blur' }
        ],
        phoneNumber: [
          {
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          },
          {
            pattern: /0?(13|14|15|18|17)[0-9]{9}/,
            message: '手机号格式不对',
            trigger: 'blur'
          }
        ],
        telForRelatives: [
          {
            required: true,
            message: '请输入家属手机号',
            trigger: 'blur'
          },
          {
            pattern: /0?(13|14|15|18|17)[0-9]{9}/,
            message: '手机号格式不对',
            trigger: 'blur'
          }
        ],
        nameForRelatives: [
          {
            required: true,
            message: '请输入家属名字',
            trigger: 'blur'
          }
        ]
      },
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 用户表格数据
      elderlyList: null,
      // 总条数
      total: 0,
      // 选中数组
      ids: [],
      // 表单参数
      form: {
        id: '',
        name: '',
        identityId: '',
        weight: undefined,
        height: undefined,
        phoneNumber: '',
        address: '',
        sex: '',
        userId: '',
        telForRelatives: '',
        nameForRelatives: '',
        age: ''
      }
    }
  },
  watch: {},
  created() {
    this.getList()
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加老人'
    },
    /** 导出按钮操作 */
    handleExport() {
      this.$modal.confirm('是否确认导出所有数据？').then(() => {
        this.exportLoading = true
        return exportElderly()
      }).then(response => {
        // this.$download.name(response.msg)
        this.exportLoading = false
      }).catch(() => {})
    },
    handleUpload(file) {
      const loading = this.$loading({
        lock: true,
        text: '正在上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      uploadExcel(file.file).then((response) => {
        loading.close()
        this.$message.success('上传成功')
        this.getList()
      }).catch(error => {
        loading.close()
        this.$message.error(error.msg)
      })
    },
    handleBeforeUpload(file) {
      var suffix = file.name.substr(file.name.lastIndexOf('.'))
      if (suffix !== '.xls' && suffix !== '.xlsx') {
        this.$message.error('请上传Excel文件,后缀.xls .xlsx')
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listElderly(this.queryParams).then((response) => {
        this.elderlyList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getElderly(id).then((response) => {
        this.userList = []
        this.form = response
        if (response.user) {
          this.userList.push(response.user)
        }
        this.open = true
        this.title = '修改老人信息'
      })
    },
    // 表单重置
    reset() {
      this.form = {
        name: undefined,
        identityId: undefined,
        weight: undefined,
        height: undefined,
        phoneNumber: undefined,
        address: undefined,
        sex: undefined,
        userId: undefined,
        telForRelatives: undefined,
        nameForRelatives: undefined,
        age: undefined
      }
      this.resetForm('form')
    },
    searchInput(query) {
      queryUser({ query: query }).then(res => {
        this.userList = res
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除用户编号为"' + ids + '"的数据项？')
        .then(function() {
          return delElderly(ids)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid, error) => {
        if (valid) {
          if (this.form.id !== undefined) {
            updateElderly(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addElderly(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        } else {
          return
        }
      })
    }
  }
}
</script>
